package com.laikan.reader.core.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.*;
import android.graphics.Bitmap.Config;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import com.laikan.reader.R;
import com.laikan.reader.core.LaikanApplication;
import com.socks.library.KLog;
import org.joda.time.DateTime;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PublicUtil {

    public static AlertDialog mAlertDialog;

    /**
     * 以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     *
     * @return </br>修改为</br>
     * imageButton_fav.setImageBitmap(BitmapUtils.readBitMap(this,
     * R.drawable.guide_fav_1));
     */
    @SuppressWarnings ("deprecation")
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        try {
            InputStream is = context.getResources().openRawResource(resId);
            return BitmapFactory.decodeStream(is, null, null);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提取图像Alpha位图并设置颜色
     *
     * @param mBitmap
     * @param mColor
     *
     * @return
     */
    public static Bitmap getAlphaBitmap(Bitmap mBitmap, int mColor) {
        //    	BitmapDrawable mBitmapDrawable = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.enemy_infantry_ninja);
        //    	Bitmap mBitmap = mBitmapDrawable.getBitmap();

        //BitmapDrawable的getIntrinsicWidth（）方法，Bitmap的getWidth（）方法
        //注意这两个方法的区别
        //Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmapDrawable.getIntrinsicWidth(), mBitmapDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Config.ARGB_8888);

        Canvas mCanvas = new Canvas(mAlphaBitmap);
        Paint mPaint = new Paint();

        mPaint.setColor(mColor);
        //从原位图中提取只包含alpha的位图
        Bitmap alphaBitmap = mBitmap.extractAlpha();
        //在画布上（mAlphaBitmap）绘制alpha位图
        mCanvas.drawBitmap(alphaBitmap, 0, 0, mPaint);

        return mAlphaBitmap;
    }

    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hideSoftMethod(Activity activity) {

        try {
            // 隐藏软键盘
            ((InputMethodManager)(activity.getSystemService(Context.INPUT_METHOD_SERVICE))).hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 产生随机数
     *
     * @param start
     * @param end
     *
     * @return
     */
    public static String getRandomString(int start, int end) {
        return String.valueOf(Math.round(Math.random() * (end - start) + start));
    }

    public static int getBarColor(Context context, String typeColor) {
        if (TextUtils.isEmpty(typeColor)) {
            return context.getResources().getColor(R.color.C_000000);
        }else {
            String[] temps = typeColor.split("");
            String s1 = temps[2] + "" + temps[3];
            String s2 = temps[4] + "" + temps[5];
            String s3 = temps[6] + "" + temps[7];
            int i1 = Integer.parseInt(s1, 16);
            int i2 = Integer.parseInt(s2, 16);
            int i3 = Integer.parseInt(s3, 16);
            return Color.rgb(i1, i2, i3);
        }
    }

    /**
     * dp转px
     * 根据手机的分辨率从 dp 的单位转成为 px(像素)
     *
     * @param context
     * @param dipValue
     *
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }

    /**
     * px 转 dp
     * 根据手机的分辨率从 px(像素)的单位 转成为 dp
     *
     * @param context
     * @param pxValue
     *
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }

    /**
     * 隐藏提示弹框
     */
    public static void hideAlertDialog() {
        if (null != mAlertDialog) {
            mAlertDialog.dismiss();
        }
    }

    /**
     * 获取assets目录下的内容
     *
     * @param fileName assets目录下的文件名称
     *
     * @return
     */
    public static String getFromAssets(Context context, String fileName) {
        String Result = "";
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                Result += line;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result;
    }

    /**
     * 获取屏幕密度
     *
     * @return 密度
     */
    public static float getDensity() {
        float density = LaikanApplication.applicationContext.getResources().getDisplayMetrics().density;
        return density;
    }

    /**
     * 图片放大 (针对一些背景是小图，并且不均匀的，只能进行放大操作)
     *
     * @param bitmap 要放大的bitmap
     * @param w 要缩放的宽
     * @param h 要缩放的高
     *
     * @return 缩放后的bitmap
     *
     * @date 2015-10-30 上午9:49:31
     * @author yjh
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h) {
        if (bitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int newWidth = w;
            int newHeight = h;
            float scaleWidth = ((float)newWidth) / width;
            float scaleHeight = ((float)newHeight) / height;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            return resizedBitmap;
        }else {
            return null;
        }
    }

    /**
     * 图片平铺 针对小图并且均匀的图片
     */
    public static Bitmap createRepeater(int width, int height, Bitmap src) {
        int x = (width + src.getWidth() - 1) / src.getWidth();
        int y = (height + src.getHeight() - 1) / src.getHeight();
        // 定义一个全局的图片背景
        Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        // 计算宽高并填充画布
        for (int i = 0; i < y; i++) {

            for (int idx = 0; idx < x; ++idx) {
                canvas.drawBitmap(src, idx * src.getWidth(), i * src.getHeight(), null);
            }
        }

        return bitmap;
    }

    /**
     * .9图片绘制
     */
    public static void drawNinepath(Canvas c, Rect r1, Bitmap bmp) {
        NinePatch patch = new NinePatch(bmp, bmp.getNinePatchChunk(), null);
        patch.draw(c, r1);
    }

    /**
     * 判断当前网络是否连接
     *
     * @param context ctx
     *
     * @return true-->已连接 ;false -->未连接
     */
    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null) {
            return false;
        }
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        return netinfo != null && netinfo.isConnected();
    }

    public static String getMetaData(Context context, String metaDataKey) {
        ApplicationInfo appInfo = null;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        }catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (appInfo != null) {
            return appInfo.metaData.getString(metaDataKey);
        }
        return "";
    }

    public static int[] measureView(View view) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        int height = view.getMeasuredHeight();
        int width = view.getMeasuredWidth();
        return new int[]{width, height};
    }

    /*
    * 设置控件所在的位置YY，并且不改变宽高，
    * XY为绝对位置
    */
    public static void setLayout(View view, int x, int y) {
        ViewGroup.MarginLayoutParams margin = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
        margin.setMargins(x, y, margin.rightMargin, margin.bottomMargin);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin);
        view.setLayoutParams(layoutParams);
    }

    /**
     * 获取根路径
     *
     * @return
     */
    public static File getRootPath() {
        File file = FileUtil.isHaveSDCard() ? Environment.getExternalStorageDirectory() : Environment.getDataDirectory();
        return file;
    }

    public static File getFile(String filePath) {
        File file = new File(getRootPath().getPath() + filePath);
        return file;
    }

    /**
     * 时间戳转成字符串
     *
     * @param time 时间戳
     *
     * @return 字符串 时间
     */
    public static String getDateToString(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sf.format(d);
    }

    /**
     * 将字符串转为时间戳
     *
     * @param time 字符串时间
     *
     * @return 长整型 时间戳
     */

    public static long getStringToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        }catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    /**
     * 将图片转化为二进制的方法
     *
     * @param bitMap 要转换的图片
     *
     * @return byte数组的字符串表示
     */
    public static byte[] changeBitmapToByte(Bitmap bitMap) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.PNG, 100, bos);
        return bos.toByteArray();
    }

    /**
     * 将二进制转化为图片的方法
     *
     * @param b
     *
     * @return
     */
    public static Bitmap changeByteToBitmap(byte[] b) {
        Bitmap bitmap = null;
        if (b.length != 0) {
            bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        }
        return bitmap;
    }

    /**
     * 判断参数是否为全部为数字<br>
     * </br> 减少字符串转数字时的错误<br>
     * </br> 此方法可使用于直接进行转换时
     *
     * @param s 要判断的参数
     *
     * @return 如果全部为数字，返回原有字符串，否则返回"0"，参数为null，依然返回"0"
     */
    public static String isNum(String s) {
        if (TextUtils.isEmpty(s)) {
            return "0";
        }
        return isNumForBoolean(s) ? s : "0";
    }

    /**
     * 判断参数是否为全部为数字，全数字，意味着不能存在小数点，及不能判断double和float<br>
     * </br> 减少字符串转数字时的错误<br>
     * </br> 此方法可使用于判断是否为全是数字的字符串
     *
     * @param s 要判断的参数
     *
     * @return true 全部为数字，否则返回false
     */
    public static boolean isNumForBoolean(String s) {
        // 为空，不是数字，返回false
        return !TextUtils.isEmpty(s) && s.matches("\\d+");
    }

    /**
     * 此方法接受UNIX时间戳，并且只可接受此类时间戳。<br></br>
     * <b>UNIX时间戳：</b>什么是Unix时间戳(Unix timestamp)： Unix时间戳(Unix timestamp)，<br></br>
     * 或称Unix时间(Unix time)、POSIX时间(POSIX time)，是一种时间表示方式，<br></br>
     * <b>定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。</b><br></br>
     * Unix时间戳不仅被使用在Unix系统、类Unix系统中，也在许多其他操作系统中被广泛采用<br></br>
     *
     * @param timestampString 时间戳
     * @param formats 需要转化的格式：例如 yyyy-MM-dd
     *
     * @return 日期
     *
     * @deprecated 限于此方法的局限性(只接受UNIX时间戳)以及命名问题，建议使用{@link #timeStamp2DateFormatString(String, String)}
     */
    public static String TimeStamp2Date(String timestampString, String formats) {
        return timeStamp2DateFormatString(timestampString + "000", formats);
    }

    /**
     * 时间戳转换为格式化的字符串<br></br>
     * 时间戳：为java程序默认的样式，和UNIX时间戳（精确至秒）不同，java时间戳精确至毫秒。<br></br>
     * 一般来说UNIX时间戳乘以1000，即为java程序默认时间戳<br></br>
     * 格式化：的字符串写法可参考{@link java.text.SimpleDateFormat}类的注释
     *
     * @param timeStamp java格式时间戳
     * @param format 需要显示的格式
     *
     * @return 格式化后的数据
     */
    public static String timeStamp2DateFormatString(String timeStamp, String format) {
        return timeStamp2DateFormatString(Long.parseLong(isNum(timeStamp)), format);
    }

    /**
     * 参考{@link #timeStamp2DateFormatString(String, String)}方法注释
     */
    public static String timeStamp2DateFormatString(long timeStamp, String format) {
        String temp = "";
        try {
            temp = new DateTime(timeStamp).toString(format);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }

    /**
     * 显示软键盘
     */
    public static void showMethod(Activity activity) {

        InputMethodManager imm = (InputMethodManager)activity.getSystemService(FragmentActivity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 判断是否存在SD卡
     *
     * @return true，有SD卡。false，无SD卡
     */
    public static boolean isHaveSDCard() {
        String SDState = android.os.Environment.getExternalStorageState();
        return SDState.equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 验证邮箱是否合法
     *
     * @param email
     *
     * @return
     */
    public static boolean isEmail(String email) {
        // final String str =
        // "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
        // final String str = "\\w+@(\\w+.)+[a-z]{2,3}";
        final String str = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        // final String str =
        // "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
        // final Pattern p = Pattern.compile(str);
        // final Matcher m = p.matcher(email);
        // KLog.i(m.matches() + "---");
        return email.matches(str);
    }

    /**
     * 验证手机号是否正确
     *
     * @param phoneNum
     *
     * @return
     */
    public static boolean isCellphone(String phoneNum) {
        // final String parrern1 = "^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$";
        // final Pattern pattern = Pattern.compile(parrern1);
        // final Matcher matcher = pattern.matcher(str);
        // if (matcher.matches()) {
        // return true;
        // }
        return phoneNum.matches("^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$");
    }

    /**
     * 验证身份证是否合法
     *
     * @param IDCard
     *
     * @return
     */
    public static boolean isIDcard(String IDCard) {
        // final String pattern =
        // "^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";
        // final Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        // final Matcher matcher = p.matcher(idStr);
        // if (matcher.matches()) {
        // return true;
        // }
        return IDCard.matches("^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$");
    }

    /**
     * 将文件存到sd卡目录
     *
     * @param data
     * @param filePath
     */
    public static void saveDatatoLocalFile(String data, String filePath) {
        if (!TextUtils.isEmpty(data) && !TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file != null && file.exists()) {
                file.delete();
            }
            FileOutputStream outStr = null;
            try {
                if (file.createNewFile()) {
                    outStr = new FileOutputStream(file);
                    if (outStr != null) {
                        outStr.write(data.getBytes());
                        outStr.flush();
                    }
                    KLog.i("----saveDatatoLocalFile---------", " file path" + filePath);
                }
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                if (outStr != null) {
                    try {
                        outStr.close();
                    }catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }finally {
                        outStr = null;
                    }
                }
            }

        }
    }
}
